package xyz.kongbai121.shop.search.thread;

import java.util.concurrent.*;

public class ThreadTest {

    //线程池
    public static ExecutorService pool = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        System.out.println("开始");
//        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//            System.out.println("当前线程: " + Thread.currentThread().getId());
//        }, pool);

        //方法执行后的感知
//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程: " + Thread.currentThread().getId());
//            return 10 / 0;
//        }, pool).whenComplete((res,excption)->{
//            // 虽然能得到异常信息, 但没法修改返回结果
//            System.out.println("异步任务完成了.......结果是:"+res+";异常是:"+excption);
//        }).exceptionally(throwable -> {
//            //可以感知异常,同时返回默认值
//            return 10;
//        });
//        Integer integer = future.get();

        //方法执行后的处理
//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程: " + Thread.currentThread().getId());
//            return 10 / 4;
//        }, pool).handle((res,thr)->{
//            if (res!=null){
//                return res * 2;
//            }
//            if (thr!= null){
//                return 0;
//            }
//            return 0;
//        });
//        System.out.println(future.get());

        // 线程串行化
//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程: " + Thread.currentThread().getId());
//            return 10 / 4;
//        }, pool).thenApplyAsync((res) -> {
//            Syst
//            em.out.println("任务2启动了..." + res);
//            return res;
//        }, pool);
//        System.out.println(future.get());
        CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程: " + Thread.currentThread().getId());
            return 10 / 4;
        }, pool);
        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程: " + Thread.currentThread().getId());
            return "hello";
        }, pool);

        future01.thenAcceptBothAsync(future02, (integer,string)->{
            System.out.println(integer+"任务3开始"+string);
        },pool);
        System.out.println("结束");
    }

}
